<template>
	<view class="content">
		<global-notify></global-notify>
		
		<view style="padding: 1rem 1rem 6px 1rem">
			<u-swiper showTitle indicatorActiveColor='#007aff' indicator height='180' indicatorMode="line" circular
				:list="listSwiper"></u-swiper>
		</view>

		<view style="padding: 6px 1rem " v-if="panelData.length>0">
			<self-card title='咨询模式'>
				<!-- <template slot="titleExt">titleExt</template> -->
				<template slot="content">
					<view class="icTypeItems">
						<view v-for="icType in panelData" class="icTypeItem">
							<view class="icTypeItemData">
								<view class="value">{{todayData[icType.value] || 0}}<span class="unit">单</span></view>
								<view :class="'icon ' + icType.value"></view>
							</view>
							<view class="icTypeItemLabel">{{`今日${icType.label}数`}}</view>
							<view v-if="icType.needPlan && (systemRoles || []).indexOf(icType.systemRole) >= 0">
								<u-switch asyncChange size="20" v-model="lawyerStatus[icType.value]"
									@change="(e) => {asyncChange(e, icType)}"></u-switch>
							</view>
						</view>
					</view>
				</template>
			</self-card>
		</view>

		<view style="padding: 6px 1rem;">
			<u-notice-bar customStyle="border-radius: 8px; " direction='column' icon='pushpin-fill' color='#0668F2'
				bgColor='#fff' :text="notice"></u-notice-bar>
		</view>
		<view class="calendarContainer" style="padding: 6px 1rem 1rem 1rem;">
			<zui-calendar v-if="loadingC" :extraData="extraData" @click-active="clickActive">
			</zui-calendar>
		</view>

		<u-action-sheet :round="10" :title="`${selectDate.date}班次信息`" @close="closePlans" :show="showPlans">
			<slot>
				<view class="plansContainer" v-if="planList && planList.length > 0">
					<u-cell-group>
						<u-cell v-for="plan in planList" :title='plan.title'>
							<u-icon slot="icon" size="28" name="calendar" :color='plan.color'></u-icon>
							<view slot='label'>
								{{plan.date}} {{$moment(plan.start).format('HH:mm:ss')}}至{{$moment(plan.end).format('HH:mm:ss')}}
							</view>
						</u-cell>
					</u-cell-group>
				</view>
				<view v-else>
					<u-empty mode="data" text='暂无班次'>
					</u-empty>
				</view>
			</slot>
		</u-action-sheet>
	</view>
</template>

<script>
	import {
		toast,
		clearStorageSync,
		setStorageSync,
		getStorageSync,
		useRouter
	} from '@/utils/utils.js'
	export default {
		data() {
			return {
				showPlans: false,
				panelData: [],
				systemRoles: [],
				icTypes: [],
				listSwiper: [
					'/static/images/swiper/swiper1.png',
					'/static/images/swiper/swiper1.png'
				],
				todayData: {},
				lawyerStatus: uni.getStorage('lawyerStatus') || {},
				calendarPlans: {},
				loadingC: false,
				planList: [
					// {
					// 	avatar: 'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-uni-app-doc/6acec660-4f31-11eb-a16f-5b3e54966275.jpg',
					// 	title: '整理会议记录文档1',
					// 	time: '45分钟',
					// 	details: '首要任务',
					// 	date: '10:30'
					// },
					// {
					// 	avatar: 'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-uni-app-doc/6acec660-4f31-11eb-a16f-5b3e54966275.jpg',
					// 	title: '整理会议记录文档',
					// 	time: '45分钟',
					// 	details: '首要任务',
					// 	date: '10:30'
					// },
					// {
					// 	avatar: 'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-uni-app-doc/6acec660-4f31-11eb-a16f-5b3e54966275.jpg',
					// 	title: '整理会议记录文档',
					// 	time: '45分钟',
					// 	details: '首要任务',
					// 	date: '10:30'
					// }
				],
				upDatakey: '', //为重新渲染DOM值，入不需要则可取消
				extraData: [],
				selectDate: {}
			}
		},
		computed: {
			isAdmin: function() {
				return (this.systemRoles || []).indexOf('admin') >= 0
			},
			hasOperationRole: function() {
				return (this.systemRoles || []).indexOf('OPERATION_MANAGER') >= 0 || (this.systemRoles || []).indexOf(
					'OPERATION') >= 0
			},
			hasLawyerM: function() {
				return (this.systemRoles || []).indexOf('LAWYER_MANAGER') >= 0
			},
			notice: function() {
				return ["若停止接单，请及时下线！"]
			},
		},
		methods: {
			// 点击日数方法
			clickActive({
				item,
				index
			}) {
				console.log(index, item)
				this.selectDate = item
				this.planList = item.data || []
				if (this.planList.length > 0) {
					this.showPlans = true
				}
			},
			closePlans: function() {
				this.showPlans = false
				this.planList = []
			},
			// 点击任务方法
			clickTask({
				row,
				index
			}) {
				console.log(row, index)
			},
			getLawyerAllStatus: function() {
				let that = this
				that.$api.getLawyerAllStatus().then(res => {
					if (res.success) {
						this.lawyerStatus = res.result || {}
						uni.setStorageSync('lawyerStatus', res.result || {})
					} else {
						toast(res.message)
					}
				}).catch(function(err) {
					console.log('getLawyerAllStatus err', err)
				})
			},
			asyncChange(e, icType) {
				if (this.lawyerStatus[icType.value]) {
					//当前在线
					uni.showModal({
						content: '确定要下线吗',
						success: (res) => {
							if (res.confirm) {
								this.changeLawyerStatus(icType.value, e)
							}
						}
					})
				} else {
					this.checkLawyerPlan(icType.value).then(val => {
						console.log('checkLawyerPlan-' + icType.value, val)
						if (val) {
							this.changeLawyerStatus(icType.value, true).then(val => {}).catch(err => {})
						}
					})
				}
			},
			changeLawyerStatus: function(type, status) {
				let that = this
				return new Promise((resolve, reject) => {
					that.$api.changeLawyerStatus({
						"schedulingPlanType": type,
						"online": status
					}).then(res => {
						if (res.success) {
							that.lawyerStatus[type] = status
							if (status) {
								toast("上线成功！")
							} else {
								toast("您已下线！")
							}
							resolve()
						} else {
							toast(res.message)
							reject(res.message)
						}
					}).catch(function(err) {
						console.log('changeLawyerStatus error', err)
						toast("操作失败！")
						reject(err)
					})
				})
			},
			checkLawyerPlan: function(type) {
				let that = this
				return new Promise((resolve, reject) => {
					that.$api.checkLawyerPlan({
						schedulingPlanType: type
					}).then(res => {
						if (res.success) {
							if (!res.result) {
								toast('不在抢单时间段内， 无法上线！')
							}
							resolve(res.result)
						} else {
							toast(res.message)
							resolve(false)
						}
					}).catch(function(err) {
						toast('验证班次失败！')
						resolve(false)
					})
				})
			},
			getICTypes: async function() {
				this.icTypes = await this.$commonData.getICTypes()
			},
			getSystemRoles: async function() {
				this.systemRoles = await this.$commonData.getSystemRoles()
			},
			loadTodayData: function() {
				this.$api.todayData().then(res => {
					if (res.success) {
						this.todayData = res.result || {}
					} else {
						toast(res.message)
					}
				})
			},
			getCalendarPlans: function() {
				this.loadingC = false
				this.$api.getCalendarPlans().then(res => {
					if (res.success) {
						this.calendarPlans = res.result || {}
						this.extraData = res.result?.dayEvent || []
					} else {
						toast(res.message)
					}
				}).finally(() => {
					setTimeout(() => {
						this.loadingC = true
					}, 500)
				})
			},
			getSwiper: function(){
				this.$api.page({pageType: 'homeSwiper'}).then(res => {
					if (res.success) {
						let result = res.result || {}
						this.listSwiper = result.data || []
					} else {
						toast(res.message)
					}
				}).finally(() => {
					if(this.listSwiper.length == 0){
						this.listSwiper= [{url: '/static/images/swiper/swiper1.png'}]
					}
				})
			}
		},
		onPullDownRefresh() {
			console.log('refresh');
			this.getSwiper()
			Promise.all([this.getLawyerAllStatus(),
				this.loadTodayData(),
				this.getCalendarPlans()
			]).finally(() => {
				uni.stopPullDownRefresh();
			})
		},
		onTabItemTap() {
			console.log('onTabItemTap')
			this.getLawyerAllStatus()
		},
		onLoad() {
			Promise.all([this.getICTypes(), this.getSystemRoles()]).then(val => {
				this.panelData = this.icTypes.filter(icType => {
					console.log('icType', icType)
					return icType.isOpen && ((this.systemRoles || []).indexOf(icType.systemRole) >= 0 || this
						.hasOperationRole || this.isAdmin)
				})
			})
			uni.startPullDownRefresh();
		}
	}
</script>
<style scoped lang="scss">
	.content {
		// padding: 1rem;
		height: 100%;
		overflow-y: auto;

		.icTypeItems {
			display: flex;
			margin-top: 10px;
			flex-wrap: wrap;

			.icTypeItem {
				overflow: hidden;
				position: relative;
				border-radius: 4px;
				background: #EEF8FF;
				border: 1px solid #EEF8FF;
				margin-right: 10px;
				margin-bottom: 10px;
				flex: 1;
				min-width: fit-content;
				padding: 1rem;

				.icTypeItemData {
					display: flex;
					justify-content: space-between;
					align-items: flex-end;
					margin-bottom: 10px;

					.value {
						color: #0484f4;
						font-family: "PingFang SC";
						font-size: 24px;
						font-style: normal;
						font-weight: 600;
						line-height: 20px;

						.unit {
							font-size: 12px;
							font-style: normal;
							font-weight: 400;
							margin-left: 2px;
						}
					}

					.icon {
						width: 22px;
						height: 22px;
						background-position: center;
						background-repeat: no-repeat;
						background-size: 100% 100%;
					}

					.IM {
						background-image: url('/static/images/imIcon.png');
					}

					.MC {
						background-image: url('/static/images/mcIcon.png');
					}

					.HL {
						background-image: url('/static/images/hlIcon.png');
					}
				}

				.icTypeItemLabel {
					color: #404863;
					font-family: "PingFang SC";
					font-size: 12px;
					font-style: normal;
					font-weight: 400;
					line-height: 20px;
				}

			}

			.icTypeItem:last-child {
				margin-right: 0;
			}

			.icTypeItem::after {
				content: "";
				width: 90px;
				height: 90px;
				flex-shrink: 0;
				border-radius: 90px;
				background: linear-gradient(317deg, #FFF 63.82%, #ffffff00 84.13%);
				position: absolute;
				right: -45px;
				bottom: -45px;
			}

			.icTypeItem::before {
				content: "";
				position: absolute;
				left: -18px;
				top: -32px;
				width: 64px;
				height: 64px;
				flex-shrink: 0;
				border-radius: 64px;
				background: linear-gradient(130deg, #FFF 54.65%, #ffffff00 73.54%);
			}
		}

		.plansContainer {
			text-align: left;
		}
	}
</style>